package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"week3/cache"
	"week3/models"
)

type AdsController struct {
	beego.Controller
}

// msg
type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 广告添加
func (c *AdsController) Add() {
	//接收数据
	title := c.GetString("title")
	plays := c.GetString("plays")
	address := c.GetString("address")
	status := c.GetString("status")

	//为空验证
	if title == "" || plays == "" || address == "" || status == "" {
		res := Response{
			Code: 500,
			Msg:  "参数不能为空",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	//数据入库
	ads := models.Ad{
		Title:   title,
		Plays:   plays,
		Address: address,
		Status:  status,
	}

	//调用方法，实现添加
	if ads.Add() != nil {
		res := Response{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	//同步redis数据
	cacheData, _ := ads.List()
	jsonData, _ := json.Marshal(&cacheData)
	cache.Rdb.Set(cache.Ctx, "ad_add", jsonData, 0)

	res := Response{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return

}

// 广告列表展示
func (c AdsController) List() {
	//接收数据
	cacheData := cache.Rdb.Get(cache.Ctx, "ad_list").Val()
	//接收结构体
	var ads []*models.Ad

	if cacheData == "" {
		fmt.Println("从Redis获取")
		models.DB.Find(&ads)
		jsonData, _ := json.Marshal(&ads)
		cache.Rdb.Set(cache.Ctx, "ad_list", jsonData, 0)
	} else {
		//反序列化
		fmt.Println("从mysql中获取")
		json.Unmarshal([]byte(cacheData), &ads)
	}

	res := Response{
		Code: 200,
		Msg:  "数据获取成功",
		Data: ads,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return

}

// 广告修改
func (c *AdsController) Update() {
	//接收修改数据
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	plays := c.GetString("plays")
	address := c.GetString("address")
	status := c.GetString("status")

	//接收结构体
	var ads models.Ad
	//实现入库
	ads.ID = uint(id)
	ads.Title = title
	ads.Plays = plays
	ads.Address = address
	ads.Status = status

	//调用方法，实现修改
	if ads.Update() != nil {
		res := Response{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	//同步redis数据
	cacheData, _ := ads.List()
	jsonData, _ := json.Marshal(&cacheData)
	cache.Rdb.Set(cache.Ctx, "ad_update", jsonData, 0)

	res := Response{
		Code: 200,
		Msg:  "修改成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return

}

// 广告删除
func (c *AdsController) Del() {
	//接收id
	id, _ := c.GetInt("id")
	//接收结构体
	var ads models.Ad
	ads.ID = uint(id)
	//调用方法，实现删除
	if ads.Del(id) != nil {
		res := Response{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	//同步redis数据
	cacheData, _ := ads.List()
	jsonData, _ := json.Marshal(&cacheData)
	cache.Rdb.Set(cache.Ctx, "ad_del", jsonData, 0)

	res := Response{
		Code: 200,
		Msg:  "删除成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return

}
